const ProgressUtil = require("../utils/utils.progress");
const axios = require("axios");

const yearTime = new Date().getTime() - 1000 * 3600 * 24 * 365;

function setItem(item, data) {
    item[2] = data.legalPersonName;
    item[4] = data.phoneNumber;
    item[7] = data.regLocation;
    item[8] = data.businessScope;
    item[10] = data.industry;
}

async function getZhongTai(item) {
    try {
        const url = "http://qly-data.qianlima.com/qianliyan/info/web/enterprise/";

        let res = await axios.get(url + encodeURIComponent(item[0]));

        if (res.data.code !== "0" || res.data.result.length === 0) {
            return false;
        }
        res = res.data.result[0];
        // 超过一年取天眼查
        if (res.updateTime < yearTime) {
            return false;
        }
        setItem(item, res);
        return true;
    } catch (e) {
        console.log(e);
        return false;
    }
}

async function getTianYanCha(item) {
    try {
        const url = "http://open.api.tianyancha.com/services/open/ic/baseinfoV2/2.0";
        const headers = { Authorization: "5826afef-8b42-4d09-80e4-063551764cae" };
        let params = { keyword: item[0] };
        let res = await axios.get(url, { params, headers });
        res = res.data;
        if (res.error_code !== 0) {
            return false;
        }
        setItem(item, res.result);
        return true;
    } catch (e) {
        console.log(e);
        return false;
    }
}

async function sheetOption(sheet, tmpl) {
    let progress = ProgressUtil.getInstance(sheet.name);
    progress.setTemplate("进度：[now] / [all]");
    progress.addAll(sheet.data.length);
    const zhuangtai = "存续，在业（开业、在营、正常、经营、在营在册、有效、在业在册），迁出，迁入";
    let jyList = [];
    let ztList = [];
    let tycList = [];
    let errList = [];
    for (let index = 0; index < sheet.data.length; index++) {
        let item = sheet.data[index];
        // if (index === 0 || index > 5) {
        if (index === 0) {
            continue;
        }
        if (zhuangtai.indexOf(item[5]) === -1) {
            jyList.push(item[0]);
        } else if (await getZhongTai(item, tmpl)) {
            ztList.push(item[0]);
        } else if (await getTianYanCha(item, tmpl)) {
            tycList.push(item[0]);
        } else {
            errList.push(item[0]);
        }
        progress.addNow(1);
    }
    console.log(`sheet：${sheet.name}完成
    过期公司：${jyList.length}
    中台：${ztList.length}
    天眼查：${tycList.length}
    报错：${errList.length}`);
}

module.exports = {
    sheetOption,
};
